//
//  YFBaseServer.m
//  techand-iOS
//
//  Created by Yutian Duan on 16/7/16.
//  Copyright © 2016年 techand. All rights reserved.
//

#import "YFBaseServer.h"

@interface YFBaseServer () {

}

@end

@implementation YFBaseServer

+ (instancetype)sharedInstance {
  static YFBaseServer *instance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    instance = [[YFBaseServer alloc] init];
  });
  return instance;
}



- (void)startHTTPWithMethod:(YFRequestMethod)method
                     params:(NSDictionary *)params
                        key:(NSString *)key
                   finished:(FinishedBlock)finishedBlock
                     failed:(FailedBlock)failedBlock {
  [YFRequestManager startRequestWithMethod:method params:params key:key finished:^(id returnValue) {
    Result *result = [Result yy_modelWithJSON:returnValue];
    if (result.status != 200) {
      if ([[returnValue objectForKey:@"message"] isKindOfClass:[NSString class]]) {
        [SVProgressHUD showInfoWithStatus:[returnValue objectForKey:@"message"]];
      } else if (result.msg) {
        [SVProgressHUD showInfoWithStatus:result.msg];
      }
//      NSArray *tempArray = [result.data objectForKey:@"username"];
//      NSString *tempString = tempArray.firstObject;
//      if ([tempString isKindOfClass:[NSString class]]) {
//        [SVProgressHUD showInfoWithStatus:tempString];
//      }
    } else {
      if ([result.data isKindOfClass:[NSArray class]]) {
        if ([result.data count] == 0) {
          THLog(@"没有更多数据");
        }
      }
    }
    finishedBlock(result);
  } failed:^(id errorCode) {
    THLog(@"Failed: %@", errorCode);
    failedBlock(errorCode);
  }];
}

- (void)postDataWithParams:(NSDictionary *)params
                  andDatas:(NSArray *)dataArray
                    toFile:(NSArray *)fileArray
                       key:(NSString *)key
                  finished:(FinishedBlock)finishedBlock
                    failed:(FailedBlock)failedBlock {
  [YFRequestManager postDataWithParams:params andData:dataArray toFile:fileArray key:key finished:^(id returnValue) {
    Result *result = [Result yy_modelWithJSON:returnValue];
    finishedBlock(result);
  } failed:^(id errorCode) {
    failedBlock(errorCode);
  }];
}

- (NSDictionary *)params:(NSDictionary *)params {
  NSMutableDictionary *dic = [params mutableCopy];
  NSString *tempToken = [AppUser getToken];
  [dic setObject:@"Authen" forKey:tempToken];
  return dic;
}

- (NSString *)langKey {
  ///! 获取当前语言环境
  NSString *languageName = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] firstObject];
  
  if ([languageName containsString:@"zh"]) {
    ///! 繁体中文
    languageName = @"hkcn";
  } else {
    languageName = @"en";
  }

  return languageName;
  
}

@end
